package com.example.starter.security.util;

import com.example.starter.security.pojo.ExampleUser;
import com.example.starter.webmvc.util.WebUtil;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author 王令
 * @since 2022/8/9 22:46
 */
@UtilityClass
public class SecurityUtil {

    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public String getUsername() {
        ExampleUser user = getUser();
        return user == null? null: user.getUsername();
    }

    /**
     * 当前登录用户
     */
    public ExampleUser getUser() {
        final Authentication authentication = getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        final Object principal = authentication.getPrincipal();
        if (principal instanceof ExampleUser) {
            ExampleUser user = (ExampleUser) principal;
            user.setTenantId(WebUtil.getTenantId());
            user.setPassword(null);
            return user;
        }
        return null;
    }
}
